package cn.rwklyd.ecommerce.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import cn.rwklyd.ecommerce.anno.Log;
import cn.rwklyd.ecommerce.mapper.UserMapper;
import cn.rwklyd.ecommerce.pojo.*;
import cn.rwklyd.ecommerce.service.UserService;
import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 键盘书生
 * @date 2024/12/1
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    //根据用户名查询用户信息
    @RequestMapping("/getUserByName")
    public Result getUserByName(@RequestParam String username){
        return Result.success(userService.getUserByName(username));
    }

    //用户添加商品到购物车
    @RequestMapping("/addCart")
    public Result addCart(@RequestParam String userId,
                          @RequestParam String productId,
                          @RequestParam Integer quantity,
                          @RequestParam double totalPrice){
        userService.addCart(userId, productId, quantity, totalPrice);
        return Result.success();
    }

    //获取当前用户加入购物车中的商品
        @RequestMapping("/getCart")
    public Result getCart(@RequestParam String userId){
        List<Cart> cartList = userService.getCartList(userId);
        return Result.success(cartList);
    }

    //用户结算商品
    @PostMapping("/settlement")
    @Log
    public Result settlement(@RequestBody SettlementRequest request) throws GeneralSecurityException {
        //支付商品 购物车
        boolean settlement = userService.settlement(request);
        //发送邮件
        if(settlement){
            MailAccount mailAccount = new MailAccount();
            mailAccount.setHost("smtp.qq.com");
            mailAccount.setPort(465); // 使用 SSL/TLS 端口
            mailAccount.setAuth(true);
            mailAccount.setFrom("2458777387@qq.com");
            mailAccount.setUser("2458777387@qq.com");
            mailAccount.setPass("atzawunqctcidjfj");
            mailAccount.setSslEnable(true);

            // 设置 SSL 套接字工厂
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            mailAccount.setCustomProperty("mail.smtp.ssl.socketFactory", sf);

            List<Product> productList = new ArrayList<>();
            for (Long cartId : request.getCartIds()) {
                Cart cart = userMapper.getCartById(request.getUserId(), cartId);  // 获取购物车信息
                if (cart != null) {
                    Product product = userMapper.getProductById(String.valueOf(cart.getProductId()));  // 获取商品信息
                    if (product != null) {
                        productList.add(product);
                    }
                }
            }

            // 构建邮件内容
            StringBuilder emailContent = new StringBuilder();
            emailContent.append("<h1>您已成功下单以下商品：</h1>");
            emailContent.append("<p>总价: ").append(request.getTotalPrice()).append(" 元</p>");
            emailContent.append("<p>请耐心等待收货。</p>");
            emailContent.append("<h2>商品信息：</h2>");
            emailContent.append("<ul>");
            for (Product product : productList) {
                emailContent.append("<li>");
                emailContent.append("<img src='").append(product.getImageUrl()).append("' alt='").append(product.getName()).append("' style='width:100px;height:auto;'/>");
                emailContent.append("<span>").append(product.getName()).append("</span>");
                emailContent.append("<span> 数量: ").append(getCartQuantity(request.getUserId(), product.getProductId())).append("</span>");
                emailContent.append("</li>");
            }
            emailContent.append("</ul>");

            Users users = userService.getUserById(request.getUserId());
            // 创建邮件并发送
            MailUtil.send(mailAccount, CollUtil.newArrayList(users.getEmail()), "订单确认", emailContent.toString(), true);
        }
        return settlement ? Result.success("支付成功") : Result.error("结算失败");
    }

    // 获取购物车中商品的数量
    private int getCartQuantity(String userId, Integer productId) {
        // 获取购物车中商品的数量
        Cart cart = userMapper.getCartById(userId, Long.valueOf(productId));
        if (cart != null) {
            return cart.getQuantity();
        }else{
            return 0;
        }
    }

    // 用户查看历史订单
    @GetMapping("/getHistoryOrder")
    public Result getHistoryOrder(@RequestParam String userId){
        List<Cart> cartList = userService.getHistoryOrder(userId);
        return Result.success(cartList);
    }

    //删除历史订单信息
    @PostMapping("/deleteHistoryOrder")
    public Result deleteHistoryOrder(@RequestBody SettlementRequest request) {
        boolean allDeleted = true; // 用于标记是否所有记录都成功删除
        for (Long cartId : request.getCartIds()) {
            int rowsAffected = userService.deleteHistoryOrder(cartId, request.getUserId());
            if (rowsAffected <= 0) { // 如果没有任何记录被更新
                allDeleted = false;
                break; // 退出循环
            }
        }
        if (allDeleted) {
            return Result.success(); // 所有记录成功删除
        } else {
            return Result.error("删除失败"); // 返回失败信息
        }
    }


    //用户修改个人信息
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody Users users){
        userService.updateUser(users);
        return Result.success();
    }

}
